package com.dwjm.goods;

import com.dwjm.CommonResult;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.math.BigDecimal;

@WebServlet("/updateGood")
public class UpdateGoodServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        try {
            int id = Integer.parseInt(req.getParameter("id"));
            String title = req.getParameter("title");
            BigDecimal price = new BigDecimal(req.getParameter("price"));
            String descr = req.getParameter("descr");
            String img = req.getParameter("img");
            int state = Integer.parseInt(req.getParameter("state"));

            System.out.println("Received data: ");
            System.out.println("id: " + id);
            System.out.println("title: " + title);
            System.out.println("price: " + price);
            System.out.println("descr: " + descr);
            System.out.println("img: " + img);
            System.out.println("state: " + state);

            // mid 不修改，可以设置为0或数据库中原值（你可以扩展逻辑）
            Goods goods = new Goods(id, title, price, descr, img, state, 0);
            GoodDao goodDao = new GoodDaolpml();
            int result = goodDao.updateGood(goods);

            if (result == 1) {
                resp.getWriter().write(new Gson().toJson(CommonResult.success("更新成功")));
            } else {
                resp.getWriter().write(new Gson().toJson(CommonResult.fail(500, "更新失败")));
            }

        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write(new Gson().toJson(CommonResult.fail(400, "参数格式错误或缺失")));
        }
    }
}
